<?php
	//getting values from the request
	$usrnm = $_GET['usrnm'];
	$pswd = $_GET['pswd'];
	
	
	//mysql_connect(url , username , password)
	//url : host of the database
	//username : username of the database
	//password : password of the database
	
	//$con = mysql_connect("localhost","user1789586","adobephotoshopcs5");
	$con = mysql_connect("localhost","root");
	if(!$con)
		//if connection fails then it will be considered as warning and remaining
		//script will be executed expect the sql part
		die("could not connect ".mysql_error());

  
	//selecting the database
	mysql_select_db("db1789586-main",$con);
	
	//create table if not exist
	
	$query = 'CREATE TABLE IF NOT EXISTS sessioinDetails 
	(
	usrnm varchar(150) PRIMARY KEY,
	sessionKey varchar(32)
	)';
	
	$result = mysql_query($query);
	
	//writing mysql query to fetch a username
	$query = 'Select * FROM sessioinDetails WHERE usrnm="'.$usrnm.'"';
	
	//executing the query
	$result = mysql_query($query);
	
	$count = 0;
	
	//the while loop will run till all the row are parsed
	//if there are multiple results
	while($row = mysql_fetch_array($result)){
		$count++;
		$arr = array('result'=>'LoginSuccess');
		$arr['token'] = $row['sessionKey'];
	}
	
	if($count == 0){
		$query = 'Select * FROM usrdetails WHERE usrnm="'.$usrnm.'"';
		$result = mysql_query($query);
		
		while($row = mysql_fetch_array($result)){
			if($usrnm == $row['usrnm'] && $pswd == $row['pswd']){
				$count++;
				$sessionToken = md5(uniqid ($pswd.rand(), true));
				
				$query = "INSERT INTO sessioinDetails (usrnm, sessionKey) VALUES ('".$usrnm."','".$sessionToken."')";
				mysql_query($query);
				$arr = array('result'=>'LoginSuccess');
				$arr['token'] = $sessionToken;
			}
			else{
				$arr = array('result'=>'UsernamePasswordNotMatch');
			}
		}
	}
	//closing the connection
	mysql_close($con);
	
	//if count is 0 that means that there is no user with this name
	//send result as "UsernameNotExist"
	if($count == 0)
		$arr = array('result'=>'UsernameNotExist');
	
	//json_encode method convert the array result into json object and
	//echo will print the json object as text so that it can be recieved as
	//text at the client side that can be parsed at client side to create json object
	//everything that echoed here will be fetched as responseText at client side
	//so be carefull about what will be echoed so that it will not effect the client code
	echo json_encode($arr);
?>